<?php
namespace Modules\Taxonomy\Forms;

use MongoDB\BSON\ObjectID;

class ElementHandle
{
    public static function tagsGetValue($params)
    {
        $di = \Phalcon\Di::getDefault();
        $output = [];
        $options = $params['options'];
        $value = $params['value'];
        $outputType = 'array';
        $entityManager = $di->getShared('entityManager');
        if (!$value) {
            $value = [];
        }
        if (!is_array($value)) {
            $outputType = 'string';
            $value = explode(',', $value);
        }
        foreach ($value as $name) {
            $saveState = true;
            $term = $entityManager->get('term', [
                'conditions' => [
                    'name' => $name
                ]
            ]);
            if (!$term) {
                $term = $entityManager->get('term');
                $term->name = $name;
                $term->parent = $options['parent'];
                $term->description = $name;
                $term->other = [];
                $saveState = $term->save();
            }
            if ($saveState) {
                $output[] = $term->getId();
            }
        }

        if ($outputType == 'string') {
            $output = implode(',', $output);
        }
        return $output;
    }

    public static function tagsSetDefault($params)
    {
        $di = \Phalcon\Di::getDefault();
        $output = [];
        $value = $params['value'];
        $outputType = 'array';
        $entityManager = $di->getShared('entityManager');
        if (!$value) {
            $value = [];
        }
        if (!is_array($value)) {
            $outputType = 'string';
            $value = explode(',', $value);
        }
        foreach ($value as $item) {
            if (preg_match('|[a-z0-9]{24}|', $item)) {
                $term = $entityManager->get('term', [
                    'conditions' => [
                        '_id' => new ObjectID($item)
                    ]
                ]);
                $output[] = $term->name;
            } else {
                $output[] = $item;
            }
        }
        if ($outputType == 'string') {
            $output = implode(',', $output);
        }
        return $output;
    }
}